package com.example.guardian.home;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.guardian.R;
import com.example.guardian.myadapter.GridViewAdapter;
import com.example.guardian.myadapter.TCase;
import com.example.guardian.myadapter.T_CaseAdapter;
import com.example.guardian.myadapter.result_adapter;
import com.example.guardian.network.GetOkHttp;
import com.example.guardian.network.PostImage;
import com.example.guardian.network.PostKeywords;
import com.yinglan.scrolllayout.ScrollLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class ChatActivity extends AppCompatActivity {

    private ListView listView;

    private Animator mCurrentAnimator;
    private int mShortAnimationDuration;

    private List<TCase> tCaseList = new ArrayList<>();
    private List<Map<String, Object>> TCaseList = new ArrayList<Map<String, Object>>();
    private List pCaseList = new ArrayList<>();
    private List kind_list = new ArrayList<ArrayList<String>>();

    private T_CaseAdapter T_adapter = new T_CaseAdapter(ChatActivity.this, tCaseList);
    private GridViewAdapter picAdapter;
    private result_adapter result_adapter;

    private String kind;
    private String rate;
    private String formula;
    private String target;
    private String prevent;

    String pic_path = "";//图片位置

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_chat);
        ActionBar actionBar = getSupportActionBar();
        Context appContext = getApplicationContext();
        if (actionBar != null){
            actionBar.hide();
        }
        Button back_button = findViewById(R.id.chat_back_btn);
        ImageButton choseImage = findViewById(R.id.chat_photo);
        Button chat_search_btn = findViewById(R.id.chat_search);

        EditText words = findViewById(R.id.search_chat);
        ScrollLayout scrollLayout = findViewById(R.id.scroll_down_layout);
        choseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(ChatActivity.this,
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        2);
                Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, ActivityRequestCode.SHOW_MAP_DEPOT);
            }

        });


        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatActivity.this.finish();
            }
        });

        TextView kind_name = findViewById(R.id.kind_name);
        TextView kind_rate = findViewById(R.id.kind_rate);
        TextView kind_target = findViewById(R.id.target_people);
        TextView fomularr = findViewById(R.id.formula);
        TextView prev = findViewById(R.id.prevent);



        GridView result = (GridView) findViewById(R.id.CR_gridview) ;
        result_adapter = new result_adapter(kind_list,ChatActivity.this);

        GridView gridView = (GridView) findViewById(R.id.pic_grid);
        picAdapter = new GridViewAdapter(pCaseList, ChatActivity.this);




        picAdapter.picListener(new GridViewAdapter.picListener() {
            @Override
            public void onSpreadClick(int position) {                       //  position  是Item的位置
                View picview = findView(position, gridView);//  根据 position的下标 与 listView找到他的 View
                ImageView pic_v = picview.findViewById(R.id.imageview_item);
                Bitmap picresource = (Bitmap) pCaseList.get(position);
                zoomImageFromThumb(pic_v, picresource);
            }

        });

        // 系统默认的短动画执行时间 200
        mShortAnimationDuration = getResources().getInteger(
                android.R.integer.config_shortAnimTime);


        this.listView = (ListView) findViewById(R.id.T_List_view);


        //ListView item的展开事件
        T_adapter.setOnItemSpreadClickListener(new T_CaseAdapter.onItemSpreadListener() {
            @Override
            public void onSpreadClick(int i) {
                TCase t_item = tCaseList.get(i);
                AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
                builder.setTitle(t_item.getCase_name());
                builder.setMessage(t_item.getCase_content());
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
            }
        });

        fomularr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
                builder.setTitle("典型套路");
                builder.setMessage(formula);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();

            }
        });
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
                builder.setTitle("防范措施");
                builder.setMessage(prevent);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();

            }
        });
/*



 */


        chat_search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                tCaseList.clear();
                kind_list.clear();

                String input_words = words.getText().toString();
                if(input_words.isEmpty()){
                    Toast.makeText(getApplicationContext(),"请您输入内容",Toast.LENGTH_SHORT).show();
                }else{
                    PostKeywords.sendOkHttpRequest("http://124.220.154.99:5000/words_select",input_words,new okhttp3.Callback() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            //得到服务器返回的具体内容
                            String responseData = response.body().string();
                            //initTCase();
                            parseDiffJson(responseData);
                            showResponse(responseData);
                        }

                        @Override
                        public void onFailure(Call call, IOException e) {
                            //在这里对异常数据进行处理
                        }

                        private void showResponse(final String response) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(response.isEmpty()){
                                        Toast.makeText(getApplicationContext(),"暂无结果",Toast.LENGTH_SHORT).show();
                                    }else {
                                        if (kind_list.isEmpty()) {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivity.this);
                                            builder.setTitle("暂时安全");
                                            //builder.setMessage("暂时安全");
                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    //Toast.makeText(MainActivity.this, "??",Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                            builder.show();

                                            listView.setAdapter(T_adapter);
                                            result.setAdapter(result_adapter);
                                            setHeight.setGridViewHeight(appContext, result);
                                            setHeight.setListViewHeight(listView);
                                            kind_name.setText("暂时安全");
                                            kind_rate.setText("");
                                            kind_target.setText("");
                                            fomularr.setText("");
                                            prev.setText("");
                                            scrollLayout.setToExit();
                                        } else {
                                            listView.setAdapter(T_adapter);
                                            result.setAdapter(result_adapter);
                                            setHeight.setGridViewHeight(appContext, result);
                                            setHeight.setListViewHeight(listView);
                                            kind_name.setText(kind);
                                            kind_rate.setText(rate);
                                            kind_target.setText(target);
                                            fomularr.setText(formula);
                                            prev.setText(prevent);
                                            scrollLayout.setToOpen();

                                        }
                                    }
                                }
                            });
                        }
                    });

                }

            }
        });



    }

    //选择图片
    public interface ActivityRequestCode {
        public static final int SHOW_MAP_DEPOT = 1; //显示Android自带图库，用于选择用户自己的图片
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == ActivityRequestCode.SHOW_MAP_DEPOT
                    && resultCode == Activity.RESULT_OK)
                showYourPic(data);
        }
    }

    private void showYourPic(Intent data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        if (picturePath.equals(""))
            return;
        pic_path = picturePath; // 保存所添加的图片的路径
        returnwords(pic_path);
    }

    public void returnwords(String pic_path) {
        EditText words = findViewById(R.id.search_chat);
        if(pic_path.isEmpty()){
            Toast.makeText(getApplicationContext(),"请您选择图片",Toast.LENGTH_SHORT).show();
        }else{
            PostImage.sendOkHttpRequest("http://124.220.154.99:5000/images_select",pic_path,new okhttp3.Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //得到服务器返回的具体内容
                    String responseData = response.body().string();
                    showResponse(responseData);
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("pic","error", e);
                    //在这里对异常数据进行处理
                }

                private void showResponse(final String response) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(response.isEmpty()){
                                Toast.makeText(getApplicationContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                            }else {
                                words.setText(response);
                            }
                        }
                    });
                }
            });

        }

    }

    private void add_image(Bitmap bitmap) {
        pCaseList.add(bitmap);
    }

    private void initTCase(String Kind_name,String Case_name,String Case_content) {
        TCase tcase = new TCase(Kind_name,Case_name, Case_content);
        tCaseList.add(tcase);


    }


    private View findView(int position, GridView gridView) {
        int firstListItemPosition = gridView.getFirstVisiblePosition();
        int lastListItemPosition = firstListItemPosition
                + gridView.getChildCount() - 1;
        if (position < firstListItemPosition || position > lastListItemPosition) {
            return gridView.getAdapter().getView(position, null, gridView);
        } else {
            final int childIndex = position - firstListItemPosition;
            return gridView.getChildAt(childIndex);
        }
    }


    private void zoomImageFromThumb(ImageView imageView, Bitmap imageResId) {
        // 如果有动画正在运行，取消这个动画
        if (mCurrentAnimator != null) {
            mCurrentAnimator.cancel();
        }

// 加载显示大图的ImageView
        final ImageView expandedImageView = (ImageView) findViewById(
                R.id.expanded_image);
        expandedImageView.setImageBitmap(imageResId);


// 计算初始小图的边界位置和最终大图的边界位置。
        final Rect startBounds = new Rect();
        final Rect finalBounds = new Rect();
        final Point globalOffset = new Point();

        // 小图的边界就是小ImageView的边界，大图的边界因为是铺满全屏的，所以就是整个布局的边界。
        // 然后根据偏移量得到正确的坐标。
        imageView.getGlobalVisibleRect(startBounds);
        findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
        startBounds.offset(-globalOffset.x, -globalOffset.y);
        finalBounds.offset(-globalOffset.x, -globalOffset.y);

        // 计算初始的缩放比例。最终的缩放比例为1。并调整缩放方向，使看着协调。
        float startScale = 0;
        if ((float) finalBounds.width() / finalBounds.height()
                > (float) startBounds.width() / startBounds.height()) {
            // 横向缩放
            float startWidth = startScale * finalBounds.width();
            float deltaWidth = (startWidth - startBounds.width()) / 2;
            startBounds.left -= deltaWidth;
            startBounds.right += deltaWidth;
        } else {
            // 竖向缩放
            float startHeight = startScale * finalBounds.height();
            float deltaHeight = (startHeight - startBounds.height()) / 2;
            startBounds.top -= deltaHeight;
            startBounds.bottom += deltaHeight;
        }

        // 隐藏小图，并显示大图
        imageView.setAlpha(0f);
        expandedImageView.setVisibility(View.VISIBLE);

        // 将大图的缩放中心点移到左上角。默认是从中心缩放
        expandedImageView.setPivotX(0f);
        expandedImageView.setPivotY(0f);

        //对大图进行缩放动画
        AnimatorSet set = new AnimatorSet();
        set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left))
                .with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top))
                .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f))
                .with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f));
        set.setDuration(mShortAnimationDuration);
        set.setInterpolator(new DecelerateInterpolator());
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mCurrentAnimator = null;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                mCurrentAnimator = null;
            }
        });
        set.start();
        mCurrentAnimator = set;

// 点击大图时，反向缩放大图，然后隐藏大图，显示小图。
        final float startScaleFinal = startScale;
        expandedImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentAnimator != null) {
                    mCurrentAnimator.cancel();
                }

                AnimatorSet set = new AnimatorSet();
                set.play(ObjectAnimator
                        .ofFloat(expandedImageView, View.X, startBounds.left))
                        .with(ObjectAnimator
                                .ofFloat(expandedImageView,
                                        View.Y, startBounds.top))
                        .with(ObjectAnimator
                                .ofFloat(expandedImageView,
                                        View.SCALE_X, startScaleFinal))
                        .with(ObjectAnimator
                                .ofFloat(expandedImageView,
                                        View.SCALE_Y, startScaleFinal));
                set.setDuration(mShortAnimationDuration);
                set.setInterpolator(new DecelerateInterpolator());
                set.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        imageView.setAlpha(1f);
                        expandedImageView.setVisibility(View.GONE);
                        mCurrentAnimator = null;
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        imageView.setAlpha(1f);
                        expandedImageView.setVisibility(View.GONE);
                        mCurrentAnimator = null;
                    }
                });
                set.start();
                mCurrentAnimator = set;
            }
        });


    }
    //解析JSON
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void parseDiffJson(String json) {
        try {
            JSONArray jsonArray = new JSONArray(json);
            List PicNameList_test = new ArrayList();
            List official_case_name_lst = new ArrayList();
            JSONObject jsonObject_relative = (JSONObject) jsonArray.get(0);
            kind = jsonObject_relative.getString("m.name");
            rate = jsonObject_relative.getString("probability");
            target = jsonObject_relative.getString("m.feature");
            formula = jsonObject_relative.getString("m.routine");
            prevent = jsonObject_relative.getString("m.measure");
            for (int i = 1; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                //取出case列表
                JSONArray cases = jsonObject.getJSONArray("case");
                //取出kind列表
                JSONArray kinds = jsonObject.getJSONArray("kind");
                //Log.e("Json_word", word);
                //对case列表进行操作
                for (int c = 0; c < cases.length(); c++) {
                    JSONObject jsonObject_case = (JSONObject) cases.get(c);
                    String pics_name = jsonObject_case.getString("name");
                    PicNameList_test.add(pics_name);
                }
                //对kind列表进行操作
                for (int k = 0; k < kinds.length(); k++) {
                    JSONObject jsonObject_kind = (JSONObject) kinds.get(k);
                    //取出kind的name
                    String kind_name = jsonObject_kind.getString("name");
                    //取出kind的measure
                    String kind_measure = jsonObject_kind.getString("measure");
                    //取出kind的feature
                    String kind_feature = jsonObject_kind.getString("feature");
                    List small_kind_List = new ArrayList<String>();
                    small_kind_List.add(kind_name);
                    small_kind_List.add(kind_feature);
                    if(kind_list.contains(small_kind_List) == false) {
                        kind_list.add((ArrayList<String>) small_kind_List);
                    }
                    //取出official_case列表
                    JSONArray official_case = jsonObject_kind.getJSONArray("official_case");
                    /*Log.e("Json_kind_name", kind_name);
                    Log.e("Json_kind_measure", kind_measure);
                    Log.e("Json_kind_feature", kind_feature);*/
                    for (int o = 0; o < official_case.length(); o++) {
                        JSONObject jsonObject_official_case = (JSONObject) official_case.get(o);
                        //取出官方案例的标题
                        String official_case_name = jsonObject_official_case.getString("m.name");
                        //取出官方案例的内容
                        String official_case_details = jsonObject_official_case.getString("m.details");
                        /*Log.e("Json_kind_name", kind_name);
                        Log.e("Json_official_case_name", official_case_name);
                        Log.e("Json_case_details", official_case_details);*/
                        if(official_case_name_lst.contains(official_case_name) == false) {
                            initTCase(kind_name, official_case_name, official_case_details);
                            official_case_name_lst.add(official_case_name);
                        }
                    }
                }
            }
            List PicNameList = new ArrayList();
            PicNameList = GetTopN.topNFrequent(PicNameList_test,6);
            Log.e("pic",kind_list.toString());
            showImage(PicNameList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void showImage(List PicNameList) {
        if (PicNameList.isEmpty()) {
            Looper.prepare();
            Log.e("empty", "empty");
            Toast.makeText(getApplicationContext(), "无结果", Toast.LENGTH_SHORT).show();
            Looper.loop();
        } else {
            Context appContext = getApplicationContext();
            pCaseList.clear();
            for (int pic_num = 0; pic_num < 6; pic_num++) {
                String pic_name = (String) PicNameList.get(pic_num);
                GetOkHttp.sendOkHttpRequest("http://124.220.154.99:5000/image/" + pic_name, new okhttp3.Callback() {
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //得到服务器返回的具体内容
                        InputStream inputStream = response.body().byteStream();//得到图片的流
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        showResponse(bitmap);
                    }
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //在这里对异常数据进行处理
                    }

                    private void showResponse(final Bitmap bitmap) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                GridView gridView = findViewById(R.id.pic_grid);
                                add_image(bitmap);
                                gridView.setAdapter(picAdapter);
                                setHeight.setGridViewHeight(appContext, gridView);
                            }

                });
        }
    });
}
        }
    }

}